<template>
  <div class="logistics-container">
    <el-container>
      <el-header class="header">
        <div class="header-left">
          <h2>校园报修系统 - 后勤人员</h2>
        </div>
        <div class="header-right">
          <span>欢迎，{{ userStore.userInfo?.name }}</span>
          <el-button type="text" @click="handleLogout">
            <el-icon><SwitchButton /></el-icon>
            退出登录
          </el-button>
        </div>
      </el-header>
      
      <el-container>
        <el-aside width="200px" class="sidebar">
          <el-menu
            :default-active="activeMenu"
            class="sidebar-menu"
            @select="handleMenuSelect"
          >
            <el-menu-item index="assigned">
              <el-icon><Tools /></el-icon>
              <span>我的任务</span>
            </el-menu-item>
          </el-menu>
        </el-aside>
        
        <el-main class="main-content">
          <!-- 我的任务 -->
          <div class="assigned-section">
            <div class="section-header">
              <h3>我的报修任务</h3>
              <el-button type="primary" @click="refreshAssignedRepairs">刷新</el-button>
            </div>
            
            <el-table :data="assignedRepairs" style="width: 100%" v-loading="loading">
              <el-table-column prop="id" label="ID" width="80" />
              <el-table-column prop="title" label="标题" />
              <el-table-column prop="description" label="描述" show-overflow-tooltip />
              <el-table-column prop="location" label="地点" />
              <el-table-column prop="status" label="状态">
                <template #default="{ row }">
                  <el-tag :type="getStatusType(row.status)">
                    {{ getStatusText(row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="createTime" label="创建时间" width="180" />
              <el-table-column label="操作" width="200">
                <template #default="{ row }">
                  <el-button size="small" @click="updateRepairStatus(row)">更新状态</el-button>
                </template>
              </el-table-column>
            </el-table>
            
            <!-- 分页组件 -->
            <div class="pagination-container">
              <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[5, 10, 20, 50]"
                :total="total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </div>
        </el-main>
      </el-container>
    </el-container>
    
    <!-- 更新报修状态对话框 -->
    <el-dialog v-model="statusDialogVisible" title="更新报修状态" width="500px">
      <el-form :model="editRepairForm" label-width="80px">
        <el-form-item label="标题">
          <el-input v-model="editRepairForm.title" disabled />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="editRepairForm.description" type="textarea" disabled />
        </el-form-item>
        <el-form-item label="地点">
          <el-input v-model="editRepairForm.location" disabled />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="editRepairForm.status">
            <el-option label="待处理" value="PENDING" />
            <el-option label="处理中" value="IN_PROGRESS" />
            <el-option label="已完成" value="COMPLETED" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="statusDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveRepairStatus">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { getAssignedRepairs, updateRepair } from '../api'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()
const userStore = useUserStore()

const activeMenu = ref('assigned')
const loading = ref(false)
const assignedRepairs = ref([])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)

// 状态更新相关
const statusDialogVisible = ref(false)
const editRepairForm = reactive({
  id: null,
  title: '',
  description: '',
  location: '',
  status: ''
})

onMounted(() => {
  loadAssignedRepairs()
})

const handleMenuSelect = (index) => {
  activeMenu.value = index
}

const handleLogout = async () => {
  try {
    await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    userStore.logout()
    ElMessage.success('已退出登录')
    router.push('/login')
  } catch (error) {
    // 用户取消退出
  }
}

// 加载分配的任务
const loadAssignedRepairs = async () => {
  try {
    loading.value = true
    const response = await getAssignedRepairs()
    const allData = response.data || []
    total.value = allData.length
    
    // 客户端分页
    const startIndex = (currentPage.value - 1) * pageSize.value
    const endIndex = startIndex + pageSize.value
    assignedRepairs.value = allData.slice(startIndex, endIndex)
  } catch (error) {
    ElMessage.error('加载任务数据失败')
  } finally {
    loading.value = false
  }
}

const refreshAssignedRepairs = () => {
  currentPage.value = 1
  loadAssignedRepairs()
}

const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  currentPage.value = 1
  loadAssignedRepairs()
}

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
  loadAssignedRepairs()
}

// 更新报修状态
const updateRepairStatus = (row) => {
  Object.assign(editRepairForm, row)
  statusDialogVisible.value = true
}

const saveRepairStatus = async () => {
  try {
    await updateRepair(editRepairForm)
    ElMessage.success('状态更新成功')
    statusDialogVisible.value = false
    loadAssignedRepairs()
  } catch (error) {
    ElMessage.error('状态更新失败')
  }
}

// 工具函数
const getStatusType = (status) => {
  const types = {
    'PENDING': 'warning',
    'IN_PROGRESS': 'primary',
    'COMPLETED': 'success',
    'CANCELLED': 'info'
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    'PENDING': '待处理',
    'IN_PROGRESS': '处理中',
    'COMPLETED': '已完成',
    'CANCELLED': '已取消'
  }
  return texts[status] || status
}
</script>

<style scoped>
.logistics-container {
  height: 100vh;
}

.header {
  background: #f56c6c;
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 20px;
}

.header-right .el-button {
  color: white;
  font-weight: 500;
}

.header-right .el-button:hover {
  background-color: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
}

.sidebar {
  background: #f5f5f5;
}

.sidebar-menu {
  border-right: none;
}

.main-content {
  padding: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h3 {
  margin: 0;
  color: #333;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style> 